const db = require('better-sqlite3')('./data/delivery-management.db');

console.log('查找对象编号AA101的实例...');

// 在所有实例表中查找对象编号AA101
const tables = db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE 'device_instances_%'").all();

let foundInstance = null;
let foundTable = null;

tables.forEach(table => {
  try {
    const instances = db.prepare(`SELECT * FROM ${table.name} WHERE object_number = ?`).all('AA101');
    if (instances.length > 0) {
      foundInstance = instances[0];
      foundTable = table.name;
      console.log(`在表 ${table.name} 中找到实例:`);
      console.log(JSON.stringify(foundInstance, null, 2));
    }
  } catch(e) {
    // 跳过查询失败的表
  }
});

if (!foundInstance) {
  console.log('未找到对象编号为AA101的实例');
  console.log('\n检查所有包含A的对象编号:');
  
  tables.forEach(table => {
    try {
      const instances = db.prepare(`SELECT object_number, object_description FROM ${table.name} WHERE object_number LIKE '%A%'`).all();
      if (instances.length > 0) {
        console.log(`${table.name}:`);
        instances.forEach(inst => {
          console.log(`  ${inst.object_number} - ${inst.object_description}`);
        });
      }
    } catch(e) {
      // 跳过查询失败的表
    }
  });
} else {
  console.log('\n检查关联的参数数据...');
  
  // 查找设备信息和映射
  const deviceInfo = db.prepare('SELECT * FROM devices WHERE device_id = ?').get(foundInstance.device_type_code);
  console.log('设备信息:', JSON.stringify(deviceInfo, null, 2));
  
  if (deviceInfo) {
    const mapping = db.prepare('SELECT * FROM device_type_mappings WHERE classification_code = ?').get(deviceInfo.classification_code);
    console.log('设备映射:', JSON.stringify(mapping, null, 2));
    
    if (mapping && foundInstance.naming_record_id) {
      console.log('\n查询命名参数表:', mapping.naming_table);
      try {
        const namingData = db.prepare(`SELECT * FROM ${mapping.naming_table} WHERE id = ?`).get(foundInstance.naming_record_id);
        console.log('命名参数数据:', JSON.stringify(namingData, null, 2));
      } catch(e) {
        console.log('查询命名参数失败:', e.message);
      }
    }
  }
}

db.close();